import { forEach } from "@/util/tools";

/* 通过路由列表得到菜单列表 */
export const getMenuByRouter = (list) => {
    let res = [];
    // 循环路由列表
    forEach(list, item => {
        // 如果没有meta 或者 meta的 hideInMenu == false 创建对象
            let obj = {
                icon: (item.meta && item.meta.icon) || "",
                name: item.name,
                meta: item.meta
            };
            // 判断有没有子路由
            if (hasChild(item)) {
                // 有的话递归调用
                obj.children = getMenuByRouter(item.children)
            }
            res.push(obj)
    });
    return res
};

/* 有没有子路由 有返回true 无返回undefined */
export const hasChild = item => {
    return item.children && item.children.length !== 0;
};


/* 显示title */
export const showTitle = (item) => {
    let { title } = item.meta
    title = (item.meta && item.meta.title) || item.name
    return title
}

/* 按类查找节点 */
export const findNodeUpperByClasses = (ele, classes) => {
    let parentNode = ele.parentNode
    if (parentNode) {
        let classList = parentNode.classList
        if (classList && classes.every(className => classList.contains(className))) {
            return parentNode
        } else {
            return findNodeUpperByClasses(parentNode, classes)
        }
    }
}

/* 获取导航面包屑 */
export const getTagNavListFromLocalstorage = () => {
    const list = sessionStorage.tagNaveList
    return list ? JSON.parse(list) : []
}

/* 设置导航面包屑到内存 */
export const setTagNavListInLocalstorage = list => {
    sessionStorage.tagNaveList = JSON.stringify(list)
}

/* 获取路由title */
export const getRouteTitleHandled = (route) => {
    let router = { ...route }
    let meta = { ...route.meta }
    let title = ''
    if (meta.title) {
        if (typeof meta.title === 'function') {
            meta.__titleIsFunction__ = true
            title = meta.title(router)
        } else title = meta.title
    }
    meta.title = title
    router.meta = meta
    return router
}

/* 判断打开的标签列表里是否已存在这个新添加的路由对象 */
export const routeHasExist = (tagNavList, routeItem) => {
    let len = tagNavList.length
    let res = false
    doCustomTimes(len, (index) => {
        if (routeEqual(tagNavList[index], routeItem)) res = true
    })
    return res
}

/* 自定义时间 */
export const doCustomTimes = (times, callback) => {
    let i = -1
    while (++i < times) {
        callback(i)
    }
}

/* query判断两个路由对象是否相等 */
export const routeEqual = (route1, route2) => {
    const params1 = route1.params || {}
    const params2 = route2.params || {}
    const query1 = route1.query || {}
    const query2 = route2.query || {}
    return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}

/* 判断两个对象是否相等，这两个对象的值只能是数字或字符串 */
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1)
    const keysArr2 = Object.keys(obj2)
    if (keysArr1.length !== keysArr2.length) return false
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true
    /* eslint-disable-next-line */
    else return !keysArr1.some(key => obj1[key] != obj2[key])
}

/* 获取新路由 */
export const getNewTagList = (list, newRoute) => {
    const { name, path, meta } = newRoute
    let newList = [...list]
    if (newList.findIndex(item => item.name === name) >= 0) return newList
    else newList.push({ name, path, meta })
    return newList
}

/* 获取下一个路由 */
export const getNextRoute = (list, route) => {
    let res = {}
    if (list.length === 2) {
        res = getHomeRoute(list)
    } else {
        const index = list.findIndex(item => routeEqual(item, route))
        if (index === list.length - 1) res = list[list.length - 2]
        else res = list[index + 1]
    }
    return res
}

/* 用于找到路由列表中name为home的对象 */
export const getHomeRoute = (routers, homeName = 'home') => {
    let i = -1
    let len = routers.length
    let homeRoute = {}
    while (++i < len) {
        let item = routers[i]
        if (item.children && item.children.length) {
            let res = getHomeRoute(item.children, homeName)
            if (res.name) return res
        } else {
            if (item.name === homeName) homeRoute = item
        }
    }
    return homeRoute
}

/* 获取页面的id */
export const cyclicRouting = (menuList, rouer, callback) => {
    for (let item in menuList) {
        if (menuList[item].name == rouer.name) {
            callback(menuList[item].meta.id)
            return
        } else if (menuList[item].children.length > 0) {
            cyclicRouting(menuList[item].children, rouer, callback);
        }
    }
}

/*  设置Cookie */
export const setCookie = function (name, value) {
    let date = new Date();
    date.setTime(date.getTime() + 0.9 * 60 * 60 * 1000)
    document.cookie = name + '=' + value + ';expires=' + date.toUTCString();
}

export const getCookie = function (name) {
    var cookieName = encodeURIComponent(name) + "=",
        cookieStart = document.cookie.indexOf(cookieName),
        cookieValue = "";
    if (cookieStart > -1) {
        var cookieEnd = document.cookie.indexOf(";", cookieStart);
        if (cookieEnd == -1) {
            cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    return cookieValue;
};

/* 时间戳转时间 */
export const getdate = function (date) {
    let now = new Date(date),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ';
}

/* 数组分割 */
export const segmentation = function (list) {
    if (list.length > 0) {
        let arr = [];
        for (let item in list) {
            arr.push(list[item]);
            arr.join(',');
        }
        arr = arr.join(',');
        return arr
    } else {
        return ''
    }
}

/*  用来验证的列表 */
export function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
            return true
        }
    }
    return false
}